﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using JSTT.IPC;
using JSTT.SocketServer;

namespace JSTT.DataThreadProcess
{
    /// <summary>
    /// 接收设备数据类
    /// </summary>
    class THRecieveDevDatas
    {
        private TcpServer tcpSev = new TcpServer();
        private int tcpSevPort = 0; 
        private DTMessageQueue dtMessageSend = new DTMessageQueue();
        private int messageCount=1;
        //private NamedPipeClient namedPipeClient = new NamedPipeClient("127.0.0.1","JSTT_PIPE");

        /// <summary>
        /// 构造函数，创建消息队列，并初始化Socket准备接收数据
        /// </summary>
        public THRecieveDevDatas()
        {
            
        }

        public void ClearMessageQueue()
        {
            ///dtMessageSend.DeleteMessageQueue();
        }

        /// <summary>
        /// Thread , 打开端口,接收Socket数据
        /// </summary>
        public void ReceiveSocketDatas()
        {
            try
            {
                tcpSevPort = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["LISTENPORT"].ToString());
            }
            catch
            {
                tcpSevPort = 8899;
                JSTTLogger.Logger.ProcWarnLogger("tcpServerPort Get Error.");
            }
            tcpSev.OnConnect += TCPServer_OnConnect;
            tcpSev.OnDataAvailable += TCPServer_OnDataAvailable;
            tcpSev.Port = tcpSevPort;
            tcpSev.Open();

            // TODO : 在这里，程序应该判断端口是否被绑定，如果被绑定，应该需要返回异常信息等处理。
        }

        /// <summary>
        /// 当存在连接时，此函数被调用
        /// </summary>
        /// <param name="connection"></param>
        public void TCPServer_OnConnect(TcpServerConnection connection)
        {
            // Log 
        }

        /// <summary>
        /// 接收数据函数
        /// </summary>
        /// <param name="connection"></param>
        public void TCPServer_OnDataAvailable(TcpServerConnection connection)
        {
            // Log
            
            byte[] data = ReadStream(connection.Socket);

            if (data != null)
            {
                //namedPipeClient.SendMessage(data);
                dtMessageSend.SendMessage(data);
                JSTTLogger.Logger.RecvSocketDataLogger(data);
            }
            connection.Socket.Close();
        }


        /// <summary>
        /// 读取Socket端发送的数据
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private byte[] ReadStream(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            if (stream.DataAvailable)
            {
                byte[] data = new byte[client.Available];

                int bytesRead = 0;
                try
                {
                    bytesRead = stream.Read(data, 0, data.Length);
                }
                catch (IOException)
                {
                }

                if (bytesRead < data.Length)
                {
                    byte[] lastData = data;
                    data = new byte[bytesRead];
                    Array.ConstrainedCopy(lastData, 0, data, 0, bytesRead);
                }
                return data;
            }
            return null;
        }
    }
}
